package com.fengq1.timeaxis.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fengq1.timeaxis.core.Result;
import com.fengq1.timeaxis.dto.TimeAxisPageDTO;
import com.fengq1.timeaxis.entity.HistoryNode;
import com.fengq1.timeaxis.service.HistoryNodeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

@RestController
public class TimeAxisController {

    @Resource
    HistoryNodeService historyNodeService;

    @GetMapping
    public Result<IPage<HistoryNode>> page(@Valid TimeAxisPageDTO dto) {
        LambdaQueryWrapper<HistoryNode> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(HistoryNode::getDelFlag, 0)
                .ge(null != dto.getBeginTime(), HistoryNode::getBeginTime, dto.getBeginTime())
                .le(null != dto.getEndTime(), HistoryNode::getEndTime, dto.getEndTime());
        if (StrUtil.isNotBlank(dto.getLabels())) {
            for (String label : dto.getLabels().split(","))
                lambdaQueryWrapper.like(HistoryNode::getLabels, "<" + label + ">");
        }
        lambdaQueryWrapper.orderByAsc(HistoryNode::getBeginTime);
        IPage<HistoryNode> iPage = historyNodeService.page(new Page<>(dto.getPageNo(), dto.getPageSize(), true), lambdaQueryWrapper);
        iPage.getRecords().forEach(HistoryNode::handelLabels);
        return Result.OK(iPage);
    }
}
